import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store/index'
const request = axios.create({
  // 基地址
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000
})
// 请求拦截器
request.interceptors.request.use(config => {
  // 在请求头添加token
  config.headers.Authorization = `Bearer ${store.state.user.token}`
  return config
}, error => {
  return Promise.reject(error)
})
// 响应拦截器
request.interceptors.response.use(response => {
  // 判断业务是否成功
  if (response.data instanceof Blob) return response.data
  if (response.data.success) {
    return response.data
  } else {
    Message.error(response.data.message)
    return Promise.reject(response)
  }
}, error => {
  if (error?.response?.status === 401) {
    store.dispatch('user/logoutAction')
  }
  return Promise.reject(error)
})
export default request
